# -*- coding: utf-8 -*-
# @Time   : 2022/5/1 9:36
# @Author : lx2035
# HELLO LX

import sys
from PyQt5 import QtWidgets,QtCore,QtGui
from TCP import Ui_Form
from PyQt5.QtCore import pyqtSlot # 引入槽函数

import socket
import threading # 引入我们需要的套接字还有线程的模块


class test(QtWidgets.QWidget,Ui_Form):
    def __init__(self):
        super(test, self).__init__() # 注册初始化事件
        self.setupUi(self)
        self.setWindowTitle("demo")

    @pyqtSlot()
    def on_Listen_clicked(self):
        self.socket_listen()

    def socket_listen(self): # 监听设置
        self.server_receive = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            server_ip = self.FW_IP.text()
            server_port = int(self.FW_Port.text())
            self.server_receive.bind((server_ip, server_port))
            self.Listen.setDisabled(True)
            self.textEdit_5.append("正在监听")
        except Exception as e:
            print("请检查ip和端口号!")
            print(e)
            self.textEdit_5.append("请检查ip和端口号!")
        else:
            self.server_receive.listen(1)
            self.server_th = threading.Thread(target=self.tcp_server_connect_concurrency) # 建立服务器线程
            self.server_th.start()
            print("正在监听")
    @pyqtSlot()
    def on_btn_close_clicked(self): # 关闭连接
        if not self.Listen.isEnabled():
            self.Listen.setDisabled(False)
        try:
            send_msg = "已经断开您的连接!"
            self.server_base_connect.sendall(send_msg.encode('utf-8'))
            self.server_base_connect.close()
            self.textEdit_5.append("退出监听")
        except AttributeError as e:
            pass
        except Exception as e:
            print(e)

    @pyqtSlot()
    def on_FW_send_clicked(self): # 服务器发送数据
        send_msg = self.textEdit.toPlainText()
        self.server_base_connect.sendall(send_msg.encode('utf-8'))
        self.textEdit.clear()

    @pyqtSlot()
    def on_MB_send_clicked(self): #客户端发送数据
        send_msg = self.textEdit_3.toPlainText()
        self.client_receive.sendall(send_msg.encode('utf-8'))
        self.textEdit_3.clear()

    @pyqtSlot() # 客户端连接
    def on_btn_connect_clicked(self):
        self.client_receive = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            client_target_ip = self.MB_IP.text()
            client_target_port = int(self.MB_Port.text())
            self.client_receive.connect((client_target_ip, client_target_port))
        except Exception as e:
            self.textEdit_4.append("连接失败!请检查")
        else:
            self.btn_connect.setDisabled(True)
            client_th = threading.Thread(target=self.tcp_client_connect_concurrency)
            client_th.start()
            self.textEdit_4.append("连接成功")

    # 服务器进程
    def tcp_server_connect_concurrency(self):
        try:
            conn, addr = self.server_receive.accept()
        except Exception as e:
            print(e)
        self.server_base_connect = conn
        send_msg = "连接成功!"
        self.server_base_connect.sendall(send_msg.encode('utf-8'))
        while not self.Listen.isEnabled():
            recv_msg = self.server_base_connect.recv(1024)
            self.textEdit_2.append("客户端: " + recv_msg.decode('utf-8'))
    # 客户端进程
    def tcp_client_connect_concurrency(self):
        send_msg = "连接成功!"
        self.client_receive.sendall(send_msg.encode('utf-8'))
        while True:
            check = "已经断开您的连接!"
            recv_msg = self.client_receive.recv(1024)
            self.textEdit_4.append("服务器: " + recv_msg.decode('utf-8'))
            if recv_msg.decode('utf-8') == check:
                self.btn_connect.setDisabled(False)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    calc = test()
    calc.show()
    sys.exit(app.exec_())